package com.xinan;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.ext.render.CaptchaRender;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xinan.system.curd.AuthUser;
import com.xinan.utils.Constants;
import com.xinan.utils.DigestUtils;


import java.util.List;

@ControllerBind(controllerKey = "/")
public class IndexController extends Controller {
    @ClearInterceptor(ClearLayer.ALL)
    public void index() {
        AuthUser user = getSessionAttr(Constants.LOGIN_USER);
        if (user == null) {
            render("/WEB-INF/views/"+Constants.LOGIN_URL);
        } else {
            String menus = user.get("menus");
            if (menus != null && menus.length() > 0) {
                setAttr("menus", menus);
                setAttr("cnname", user.getCnname());
                render("/WEB-INF/views/"+Constants.INDEX_URL);
            } else {
                render("/WEB-INF/views/"+Constants.LOGIN_URL);
            }
        }
    }

    @Before(POST.class)
    public void login() {
        String userName = getPara("username");
        String passwd = getPara("passwd");
        String newpass="";
        String key =Constants.KEY;
        newpass = DigestUtils.encrypt(passwd, key);

        String page = Constants.LOGIN_URL;
            if (StringKit.notBlank(userName) && StringKit.notBlank(passwd)) {
                AuthUser user = AuthUser.dao.findByUserName(userName);
                        if(user != null && user.getYxbz().equals("0")    ){
                            setAttr("msg", Constants.LOGIN_WX);
                        }  else{
                            if (user != null && user.getPassword().equals(newpass)) {
                                String menus = buildMenu(user);
                                setAttr("menus", menus);
                                setAttr("cnname", user.getCnname());
                                user.put("menus", menus);
                                List<Record> permList = Db.find("select id,uri from auth_permission where id in(select permissionid from auth_role_permission where roleid in (select roleid from auth_user_role where userid=?) union select permissionid from auth_user_permission where userid=?)", user.getId(), user.getId());
                                user.put("perms", permList);
                                //加入缓存
            //                    CacheKit.put("sampleCache1", "perms", permList);
            //                    System.out.println ("sampleCache1"+CacheKit.get("sampleCache1", "perms"));
                                setSessionAttr(Constants.LOGIN_USER, user);
                                page = Constants.INDEX_URL;
                            } else {

                                setAttr("msg", Constants.LOGIN_ERROR);
                    }
               }
            } else {
                setAttr("msg", Constants.LOGIN_ERROR);
            }

        render(page);
//        render("mobile/index.html") ;
    }

    @ClearInterceptor(ClearLayer.ALL)
    public void logout() {
        AuthUser user = getSessionAttr(Constants.LOGIN_USER);
        if (user != null) {
            removeSessionAttr(Constants.LOGIN_USER);
        }
        render("/WEB-INF/views/login.html");
    }

    @ClearInterceptor(ClearLayer.ALL)
    public void captcha() {
        render(new CaptchaRender());
    }

    /**
     * 根据用户的权限配置，堆砌菜单树
     *
     * @param user
     * @return
     */
//    private String buildMenu(AuthUser user) {
//        List<Record> permList = Db.find("select * from auth_permission where id in(select permissionid from auth_role_permission where roleid in (select roleid from auth_user_role where userid=?) union select permissionid from auth_user_permission where userid=?) order by disp", user.getId(), user.getId());
//        StringBuilder sb = new StringBuilder();
//        for (Record r : permList) {
//            if (r.getInt("pid") == 0) {
//                sb.append("<div id='div");
//                sb.append(r.get("id"));
//                sb.append("' title='");
//                sb.append(r.get("name"));
//                sb.append("'>");
//                sb.append("<ul id='ul" + r.get("id") + "' class=\"easyui-tree\"   data-options=\"onclick:addd\">");
//                sb.append(treeHtml(permList, r.getInt("id")));
//                sb.append("</ul>");
//                sb.append("</div>");
//            }
//        }
//        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"+sb);
//        return sb.toString();
//    }
    /**
     * 根据权限内容，递归堆砌菜单树
     *
     * @param _list
     * @param pid
     * @return
     */
//    private String treeHtml(List<Record> _list, int pid) {
//        StringBuilder sb = new StringBuilder();
//        for (Record r : _list) {
//            if (pid == r.getInt("pid")) {
//                String strChild = treeHtml(_list, r.getInt("id"));
//                if (strChild.length() <= 0) {
//                    sb.append("<li  onclick=\"addTab('\" + r.get(\"name\") + \"','\" + r.get(\"uri\") + \"')\">");
//                    sb.append("<span id='span" + r.get("id") + "'  >");
//                    sb.append("<a href=\"#\" style=\"text-decoration:none;text-decoration: none; color:#000000\"  plain=\"true\" onclick=\"addTab('" + r.get("name") + "','" + r.get("uri") + "')\">");
//                    sb.append(r.get("name")+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
//                    sb.append("</a>");
//                    sb.append("</span>");
//                    sb.append("</li>");
//                } else {
//                    sb.append("<li data-options=\"state:'closed'\">"); //如果是多级树，则不进行显示
//                    sb.append("<span id='span" + r.get("id") + "'>");
//                    sb.append(r.get("name") + "");
//                    sb.append("</span>");
//                    sb.append("<ul>");
//                    sb.append(strChild);
//                    sb.append("</ul>");
//                    sb.append("</li>");
//                }
//            }
//        }
//        return sb.toString();
//    }

    private String buildMenu(AuthUser user) {
        List<Record> permList = Db.find("select * from auth_permission where id in(select permissionid from auth_role_permission where roleid in (select roleid from auth_user_role where userid=?) union select permissionid from auth_user_permission where userid=?) order by disp", user.getId(), user.getId());
        StringBuilder sb = new StringBuilder();
        sb.append("<ul class=\"nav nav-list\">");

        for (Record r : permList) {

            if (r.getInt("pid") == 0) {
//                sb.append("<div id='div");
//                sb.append(r.get("id"));
//                sb.append("' title='");
//                sb.append(r.get("name"));
//                sb.append("'>");
                sb.append("<li data-options=\"onclick:addd\">");
                sb.append("<a id='ul"+r.get("id") +"' href=\"#\" class=\"dropdown-toggle\"><i class='icon-desktop'></i><span class=\"menu-text\"><b> "+r.get("name")+"</b> </span> "+
                        "<b class=\"arrow icon-angle-down\"></b></a>");
                sb.append("<ul class=\"submenu\" >");
                sb.append(treeHtml(permList, r.getInt("id")));
                sb.append("</ul>");

                sb.append("</li>");
//                sb.append("</div>");
            }
        }
        sb.append("</ul>");

//        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"+sb);
        return sb.toString();
    }
    /**
     * 根据权限内容，递归堆砌菜单树
     *
     * @param _list
     * @param pid
     * @return
     */
    private String treeHtml(List<Record> _list, int pid) {
        StringBuilder sb = new StringBuilder();
//        sb.append("<ul class=\"submenu\">");

        for (Record r : _list) {
            if (pid == r.getInt("pid")) {
                String strChild = treeHtml(_list, r.getInt("id"));
                if (strChild.length() <= 0) {
                    sb.append("<li >");
                    sb.append("<a  href=\"#\"  onclick=\"addTab('" + r.get("name") + "','" + r.get("uri") + "','" + r.get("id") + "')\"><i class=\"icon-leaf\"></i>\n");
                    sb.append(r.get("name")+"");
                    sb.append("</a>");
                    sb.append("</li>");
                } else {
//                    System.out.println(">0"+r.get("name"));
                    sb.append("<li>"); //如果是多级树，则不进行显示
                    sb.append("<a href=\"#\"  id='a\" + r.get(\"id\") + \"'  class=\"dropdown-toggle\"><i class=\"icon-double-angle-right\"></i>\n" +
                            " <span id='span" + r.get("id") + "' class=\"menu-text\">"+r.get("name") +" </span>" +
                            "<b class=\"arrow icon-angle-down\"></b></a>");
                    sb.append("<ul class=\"submenu\"  >");

                    sb.append(strChild);
//                    sb.append("</ul>");
                    sb.append("</ul>");

                    sb.append("</li>");

                }
            }
        }
//        sb.append("</ul>");

        return sb.toString();
    }
}
